import { KeepAliveNamesState } from '@/store/interface/index';
const keepAliveStore = defineStore({
	// 这里的id必须为唯一ID
	id: 'keepAliveStore',
	state: (): KeepAliveNamesState => {
		return {
			keepAliveNames: [],
			cachedViews: [],
		};
	},
	// 等同于vuex的getter
	getters: {},
	// pinia 放弃了 mutations 只使用 actions
	actions: {
		// actions可以用async做成异步形式
		// 设置路由缓存（name字段）
		async setCacheKeepAlive(data: Array<string>) {
			this.keepAliveNames = data;
		},
		async addCachedView(view: any) {
			let routerName = view.meta?.routerName || view.name;
			if (view.meta.isKeepAlive) this.cachedViews?.push(routerName);
		},
		async delCachedView(view: any) {
			let routerName = view.meta?.routerName || view.name;
			const index = this.cachedViews.indexOf(routerName);
			index > -1 && this.cachedViews.splice(index, 1);
		},
		async delOthersCachedViews(view: any) {
			let routerName = view.meta?.routerName || view.name;
			if (view.meta.isKeepAlive) this.cachedViews = [routerName];
			else this.cachedViews = [];
		},
		async delAllCachedViews() {
			this.cachedViews = [];
		},
	},
	// 开启数据缓存
	persist: {
		enabled: true,
		strategies: [
			{
				// key可以自己定义，不填的话默认就是这个store的ID
				//key: 'user_store',
				// 保存位置，默认保存在sessionStorage storage可以填sessionStorage，localStorage
				storage: sessionStorage,
				// 指定要持久化的数据，默认所有 state 都会进行缓存，你可以通过 paths 指定要持久化的字段，其他的则不会进行持久化。
				//paths: ['userId'],
			},
		],
	},
});

export default keepAliveStore;
